<template>
    <div>
        <h1>添加{{ clazzName }}班学生信息</h1>
        <el-form :model="form" label-width="120px" @submit.prevent="submitForm">
            <el-table :data="courseSchedules" style="width: 100%; margin-bottom: 20px;">
                <el-table-column prop="studentName" label="学生信息" />
                <el-table-column prop="studentId" label="学号" />
                <el-table-column>
                    <template #default="scope">
                        <el-button type="danger" size="small" @click="removeSchedule(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-form-item label="学生姓名">
                <el-input v-model="newSchedule.studentName" placeholder="请输入学生姓名" />
            </el-form-item>
            <el-form-item label="学号">
                <el-input v-model="newSchedule.studentId" placeholder="请输入学号" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addSchedule">添加学生信息</el-button>
                <el-button type="success" @click="submitForm">提交所有学生</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import service from '@/api';
export default {
    data() {
        return {
            clazzId: null,
            clazzName: '',
            courseSchedules: [],
            newSchedule: {
                id: 0,
                studentName: '',
                studentId: '',
            }
        }
    },
    created() {
        this.clazzId = this.$route.params.clazzId;
        this.fetchClazzName();
    },
    methods: {
        async fetchClazzName() {
            const clazz = await service.get(`/api/clazz/${this.clazzId}`, null, "获取班级信息");
            this.clazzName = clazz.name;
        },
        addSchedule() {
            this.courseSchedules.push({ ...this.newSchedule });
            this.newSchedule = {
                id: 0,
                studentName: '',
                studentId: '',
            };
        },
        removeSchedule(index) {
            this.courseSchedules.splice(index, 1);
        },
        async submitForm() {
            const students = this.courseSchedules.map(schedule => ({
                name: schedule.studentName, // 字段名改为name
                number: schedule.studentId  // 字段名改为number
            }));
            await service.post(`/api/students/clazz/${this.clazzId}`, { students }, "导入学生信息"); // 添加students外层对象
            this.$message.success('学生信息导入成功！');
            this.courseSchedules = [];
        }
    }
}
</script>

<style scoped>
form div {
    margin: 10px 0;
}

label {
    display: inline-block;
    width: 80px;
}

input,
select {
    padding: 5px;
    width: 200px;
}

button {
    padding: 10px 20px;
    background-color: #42b983;
    color: white;
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: #3aa876;
}
</style>